<template>
  <a-modal
    title="发货单详情"
    :width="1300"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :footer="null"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="12" v-show="false">
            <a-form-item
              label="订单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入订单号" v-decorator="['orderNumber', {rules: [{required: false, message: '请输入订单号！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12" v-show="false">
            <a-form-item
              label="订单类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入订单类型" v-decorator="['orderType', {rules: [{required: true, message: '请输入订单类型！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12" v-show="false">
            <a-form-item
              label="源引订单Id"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入源引订单Id" v-decorator="['sourceOrderId', {rules: [{required: false, message: '请输入源引订单Id！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-table
              ref="table"
              size="default"
              style="margin-bottom: 24px"
              :columns="isDeliverToIn?deliverToInColumns:columns"
              :data-source="tableDataSource"
              :pagination="false">

              <template slot="number" slot-scope="text, record">
                <a-input v-model="record.operationNumber" placeholder="请输入数量"/>
              </template>

              <template slot="markAbnormal" slot-scope="text, record">
                <a-switch v-if="record.executeStatus == $businessEnum.EXECUTE_STATUS_ENUM.COMPLETED.id"
                          :defaultChecked="text==1"
                          :disabled="true"
                          checked-children="异常"
                          un-checked-children="正常"
                          class="scoped-switch"
                          @change="handleChangeMarkAbnormal($event, record)"/>
              </template>

              <template slot="file" slot-scope="text, record">
<!--                <a @click="">查看</a>-->
                <img v-if="text"
                  :src="`${$store.state.baseUrl}/sysFileInfo/preview?id=`+record.file+'&token='+token" style="width: 50px; height: 50px;" />
              </template>

            </a-table>
          </a-col>

          <a-col :span="24">
            <a-form-item
              label="备注"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <a-input placeholder="请输入备注" v-decorator="['remark', {rules: [{required: false, message: '请输入备注！'}]}]"
                       :disabled="true"/>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              label="上传凭证"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <a-input placeholder="请输入上传凭证" v-decorator="['file', {rules: [{required: true, message: '请输入上传凭证！'}]}]"
                       v-show="false"/>
              <fc-upload :file-list="fileList" :disabled="true" @change="uploadChange"/>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {addAllType, addSimple, page, listDetail} from '@/api/modular/main/emsorder/emsOrderManage'
import {sysDictDataSupplierList} from '@/api/modular/main/emssysdictdata/emsDictDataManage'
import FcUpload from '@/components/FCUpload/FcUpload'
import {STable} from '@/components'
import {ORDER_TYPE_ENUM} from '@/utils/util'
import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'

export default {
  components: {FcUpload, STable},
  data() {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      labelColBlock: {
        xs: {span: 24},
        sm: {span: 2}
      },
      wrapperColBlock: {
        xs: {span: 24},
        sm: {span: 20}
      },
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      fileList: [],
      orders: [],
      tableDataSource: [],
      ordersResult: [],
      orderMaterials: [],
      orgIdSupplier: 'all',
      supplierList: [],
      columns: [       // 表头
        {
          title: '序号', width:'80px',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '物料',
          dataIndex: 'materialName',
          ellipsis: true,
        },
        {
          title: '料号',
          dataIndex: 'materialCode',
          // ellipsis: true,
          width:'220px'
        },
        {
          title: '图片',
          dataIndex: 'image',
          customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
        },
        {
          title: '采购单号',
          dataIndex: 'orderNumber',
          // ellipsis: true,
          width:'220px'
        },
        {
          title: '待发数量',
          dataIndex: 'needNumber',
          customRender: (text, record, index) => `${record.number - record.completedNumber}`
          // TODO 上面这个数量还没有减去在发货中还没有入库的
        },
        {
          title: '发货数量',
          dataIndex: 'number',
          scopedSlots: {customRender: 'number'}
        },
      ],
      deliverToInColumns: [
        {
          title: '序号', width:'80px',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '物料',
          dataIndex: 'materialName',
          ellipsis: true,
        },
        {
          title: '料号',
          dataIndex: 'materialCode',
          // ellipsis: true,
          width:'220px'
        },
        {
          title: '图片',
          dataIndex: 'image',
          customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
        },
        {
          title: '采购单号',
          dataIndex: 'orderNumber',
          // ellipsis: true,
          width:'220px'
        },
        {
          title: '供应商发货数量',
          dataIndex: 'number',
          // scopedSlots: {customRender: 'number'}
        },
        {
          key: 'actualNumber',
          title: '实收数量',
          dataIndex: 'completedNumber',
          customRender: (text, record, index) => {
            return record.executeStatus == this.$businessEnum.EXECUTE_STATUS_ENUM.COMPLETED.id ? record.completedNumber : ''
          }
        },
        {
          title: '是否异常',
          dataIndex: 'markAbnormal',
          scopedSlots: {customRender: 'markAbnormal'}
        },
        {
          title: '入库图片',
          dataIndex: 'file',
          scopedSlots: {customRender: 'file'}
        },
      ],
      isDeliverToIn: false,
      emsOrder: null,
    }
  },
  computed: {
    token() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      return token
    }
  },
  methods: {
    fcsuccess(url){
        this.form.setFieldsValue({image: url})
      },
    add(record) {
      let {orderType, orders} = record
      if (!(orders && orders.length > 0)) {
        this.$message.error('请先选择采购单!')
        return
      } else {
        let EMS_ORDER_EXECUTE_STATUS_IN_PROGRESS = this.$businessEnum.EXECUTE_STATUS_ENUM.IN_PROGRESS
        let filterOrders = orders.filter(order => order.executeStatus != EMS_ORDER_EXECUTE_STATUS_IN_PROGRESS)
        if (filterOrders.length > 0) {
          this.$message.error('选择的采购单中有不在进行中状态的订单!')
          return
        }
      }

      this.emsOrder = record
      // 选中的采购单
      this.orders = orders.map(order => Object.assign({}, order))
      let orderIds = orders.map(order => order.orderId).join(',')
      // 还要调接口查采购单的物料
      this.visible = true
      // 设定订单类型
      setTimeout(() => {
        this.form.setFieldsValue(record)
        // 由于这个页面目前是专门给发货单用的,这里就硬写
        this.form.setFieldsValue({orderType: ORDER_TYPE_ENUM.deliverOrder.id})
        listDetail({orderIds}).then(res => {
          let orders = res.data
          this.orders = orders
          let oms = []
          for (const order of orders) {
            if (!order.orderMaterials) {
              continue
            }
            let _oms = order.orderMaterials.map(om => {
              let {number, completedNumber} = om
              let operationNumber = number - completedNumber
              return Object.assign({orderNumber: order.orderNumber, operationNumber}, om)
            })
            oms = oms.concat(_oms)
          }
          this.tableDataSource = oms
        })
      }, 100)
    },
    show(record) {
      // record 是发货单Bean
      let {
        orderId,
      } = record

      this.visible = true
      this.isDeliverToIn = true
      let _this = this
      this.emsOrder = record
      this.fileList = record.file.split(',').map(fileID => {
        return {
          uid: fileID,
          name: fileID,
          status: 'done',
          url: `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${fileID}&token=${this.token}`,
          fileID: fileID
        }
      })

      // 还要调接口查采购单的物料
      // 设定订单类型
      setTimeout(() => {
        // let $table = _this.$refs['table']
        // debugger
        // $table.columns = [..._this.deliverToInColumns]

        // 好像没什么好赋值的字段
        this.form.setFieldsValue(record)
        // 由于从这个方法中进入的功能属于发货单转入库仓库，硬写一下
        this.form.setFieldsValue({orderType: ORDER_TYPE_ENUM.inOrder.id, sourceOrderId: orderId})
        listDetail({orderIds: orderId}).then(res => {
          let orders = res.data
          this.orders = orders
          let oms = []
          for (const order of orders) {
            if (!order.orderMaterials) {
              continue
            }
            let _oms = order.orderMaterials.map(om => {
              let {number, completedNumber} = om
              let operationNumber = number
              return Object.assign({orderNumber: order.orderNumber, operationNumber}, om)
            })
            oms = oms.concat(_oms)
          }
          this.tableDataSource = oms
        })
      }, 100)
    },
    handleSubmit() {
      const {form: {validateFields}} = this
      this.confirmLoading = true

      validateFields((errors, values) => {
        if (!errors) {
          // 将表中的物料记录转成订单物料记录
          let _orderMaterials = this.tableDataSource.map(values => {
            let {
              orderNumber,
              operationNumber,
              orderMaterialId,
              orderId,
              sourceOrderId,
              sourceOrderMaterialId,
              bomId,
              materialId,
              number,
              completedNumber,
              executeStatus,
              executeProgress,
              file,
              remark,
              markAbnormal,
              status,
              createTime,
              createUser,
              updateTime,
              updateUser,
              materialName,
              materialCode,
              image,
            } = values
            // 接口其实只要某几个数据就好了,其它都是多余的
            return {
              // orderMaterialId: '',
              // orderId: '',
              sourceOrderId: orderId,
              sourceOrderMaterialId: orderMaterialId,
              bomId: bomId,
              materialId: materialId,
              number: operationNumber,
              // completedNumber: '',
              // executeStatus: '',
              // executeProgress: '',
              file: file,
              // remark: '',
              markAbnormal: markAbnormal,
              // status: '',
              // createTime: '',
              // createUser: '',
              // updateTime: '',
              // updateUser: '',
            }
          })
          // // 物料池ID,便于创建订单后删除
          // let materialPoolIds = this.orderMaterials.map(value => value.materialPoolId)
          let _values = Object.assign({}, values, {orderMaterials: _orderMaterials})
          // debugger
          // return
          // 本页面暂时只有发货单（由数个采购单生成）和收货单（由单个发货单生成）进入操作。订单类型由进入页面的代码来管理
          addAllType(_values).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('新增成功')
              this.handleCancel()
              this.$emit('ok', values)
            } else {
              this.$message.info('新增失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
          // }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    },
    // upload
    uploadChange(fileListString) {
      this.form.setFieldsValue({file: fileListString})
    },
    // supper
    getSupplier() {
      sysDictDataSupplierList().then(res => {
        this.supplierList = [...res.data]
      })
    },
    // switch
    handleChangeMarkAbnormal(checked, record) {
      record.markAbnormal = checked ? 1 : 0
    },
  },
  created() {
    // this.getSupplier()
  }
}
</script>
<style scoped>
.scoped-switch.ant-switch {
  background-color: #1890FF !important;
}

.scoped-switch.ant-switch-checked {
  background-color: #ff4d4f !important;
}
</style>
